/**
 * Created by Administrator on 2017-07-25.
 */
'use strict'
import Vue from 'vue'
var modelImportTemplete = require('html!./model_import_data.html');
require('./modelImportData.less');
require('../../../js/jqueryUi/jquery-ui.min.less');
require('../../../js/webupload/webuploader.less');



module.exports = {
  template: modelImportTemplete,
  data:function(){
    return{
      dataList:[],
      fileHead:[],
      fileList:[],
      initFileList:[],
      initFileCloumList:[],
      initFileNameList:[],
      userId:localStorage.getItem("userId"),
      modelId:'',
      dataHead:{},
      modelName:'',
      modelPic:''
    }
  },
  created:function(){
    this.modelId = this.$route.query.modelId;
  },
  mounted:function(){
    this.file();
    this.initUploadTableList();
  },
  beforeMount:function(){

  },
  updated:function(){
    //this.initCommonModel();
  },
  methods:{
    /**
     * 获取浏览器url参数
     * @param  {String} name 参数值
     *
     */
    getQueryString:function(name){
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]); return null;
    },
    //列表初始
    initUploadTableList:function(){
      var me = this;
      this.$http.get('/fileUploadController/getUploadTableData.do?modelId='+me.modelId+"")
        .then(function(res){
          if(res.data.status === 'OK'){
            this.initFileList = res.data.result.list;
            this.initFileCloumList = res.data.result.listCloum;
            this.initFileNameList=res.data.result.listName;
          }else{
            console.log('');
          }
        }.bind(this));
    },
    file:function(){

      var _this = this;

      var uploader = WebUploader.create({
        // swf文件路径
        swf:'http://cdn.staticfile.org/webuploader/0.1.0/Uploader.swf',
        // 文件接收服务端。
        server: Vue.prototype.$http.defaults.baseURL+'/fileUploadController/upload.do',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        auto: true,
        formData:{
          modelId:_this.modelId,
          userId: _this.userId
        },
        pick: '#picker',
        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false,
        duplicate:true,
        fileNumLimit:10,//验证文件总数量, 超出则不允许加入队列
        fileSingleSizeLimit:10*1024*1024,//验证单个文件大小是否超出限制, 超出则不允许加入队列。
        //fileSizeLimit:100*1024*1024,//验证文件总大小是否超出限制, 超出则不允许加入队列
        accept:{
          title: 'Applications',
          extensions: 'xlsx,xls,csv',
          mimeTypes: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
        }
      });


      // 当有文件被添加进队列的时候
      uploader.on( 'fileQueued', function( file ) {
        $('#thelist').html( '<div id="' + file.id + '" class="item">' +
          '<h4 class="info">' + file.name + '</h4>' +
          '<p class="state">等待上传...</p>' +
          '</div>');
      });


      // 文件上传过程中创建进度条实时显示。
      uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
          $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if ( !$percent.length ) {
          $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中...');

        $percent.css( 'width', percentage * 100 + '%' );

      });

      uploader.on( 'uploadSuccess', function( file,response) {
        if(response.code == '000000'){
          $( '#'+file.id ).find('p.state').text('已上传');
          var _fileList = [];
          _this.fileHead.push(response.result[1]);
          for(var i = 0;i<response.result[0].length;i++){
            _fileList.push(response.result[0][i]);
          }
          _this.fileList.push(_fileList);
          uploader.removeFile(file,true);
        }else{
          $( '#'+file.id ).find('p.state').text('上传失败');
          layer.msg('文件上传失败，请检查文件是否有错误！请重新上传！');
        }

      });

      uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
      });

      uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
      });
      // 所有文件上传成功后调用
      uploader.on('uploadFinished', function () {
        //清空队列
        uploader.reset();
      });


    },
    del:function(e,className){
      var _this = this;
      var me =$(e.currentTarget);
      var arry = [];
      var deleteLay = layer.confirm('是否确认删除该数据表？', {
        btn: ['是', '否'] //按钮
      }, function () {
        _this.$http.post('/fileUploadController/upload/deleteTableByName.do?className=' + className)
          .then(function (res) {
            if (res.data.code == '000000') {
              layer.msg('删除成功！');
              me.closest('dl').find('span').each(function(){
                arry.push($(this).text());
              });

              me.closest('dl').siblings('dl').find('span').removeClass('col_red');
              me.closest('dl').remove();
            } else {
              layer.msg('系统繁忙，请稍后再试');
            }
          }.bind(_this));
      });
    },

    /**
     * 点击上一步
     */
    submitPre:function () {
      var me = this;
      me.$router.push({ path: '/product/algorithmSet', query: { modelId: me.modelId+"" }});
    },

    /**
     * 点击下一步
     */
    submit:function(){
      var layLoad = layer.load(2, {shade: 0.1, area: ['32px', '64px']});
      var me = this;
      var isSubmit = false, relate = [],_relate = [];
      $('.table-main').find('dl').each(function() {
        var _this = $(this).find('dt div');
        // if (_this.text() == '') {
        //   isSubmit = false;
        //   return;
        // }
        var tableName = '';
        var tableNameVal = _this.text();
        var dataVname='';
        var dataCname='';
        $(this).find('dd').find('span').each(function () {
          if ($(this).text() != "") {
            dataVname = dataVname + $(this).text() + ";";//获取中文表头
            dataCname = dataCname + $(this)[0].dataset.cname + ";";//获取对应表字段名称
            tableName = $(this)[0].dataset.tname;
          }
        })
        relate.push({
          'tableName':tableName,
          'tableNameVal':tableNameVal,
          'dataCname':dataCname,
          'dataVname':dataVname,
        });
        isSubmit = true;
      });
      if(isSubmit){
        isSubmit = false;
        $.ajax({
          url:Vue.prototype.$http.defaults.baseURL+"/fileUploadController/saveTableInfo.do",
          method:"post",
          data:{
            'eye_model_id':me.modelId+"",
            'Relate':JSON.stringify(relate)
          },
          dataType:"json",
          success:function(res){
            layer.close(layLoad);
            if(res.code == '000000'){
              layer.msg('发送成功');
              me.$router.push({ path: '/product/modelDataExplore', query: { modelId: me.modelId,type:"add" }});
            }else{
              layer.msg('系统繁忙，请稍后再试');
            }
            isSubmit = true;
          },
          error:function(error){
            console.error(error,"error");
          }
        })
      }else{
        layer.close(layLoad);
        layer.msg('请上传数据！');
      }

    }
  }
}
